package rush.edu.wechat.admin.web.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import rush.edu.wechat.admin.web.dto.UserDto;
import rush.edu.wechat.common.utils.AccessTokenGenerator;
import rush.edu.wechat.common.utils.BCryptEncoder;
import rush.edu.wechat.facade.user.entity.User;
import rush.edu.wechat.facade.user.service.IUserService;

import java.util.concurrent.TimeUnit;

/**
 * DESC:
 * USER:hmily
 * DATE:2018/1/31
 * TIME:16:44
 */
@Component
public class AdminHandler {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private AccessTokenGenerator accessTokenGenerator;

    @Autowired
    private RedisTemplate redisTemplate;

    public UserDto loadUser(String email, String password, Boolean rememberMe){

        User loadUser = iUserService.findByEmail(email);
        //用户不存在
        if (null == loadUser){

        }

        //用户被禁止
        if (loadUser.getIsenabled() == 0 ){

        }

        boolean checkPsw = BCryptEncoder.checkPsw(password, loadUser.getPassword());
        //密码错误
        if (!checkPsw){

        }
        //登录成功
        String token = accessTokenGenerator.generate();
        String userJson = JSON.toJSONString(loadUser);
        //将用户信息存入redis
        redisTemplate.opsForValue().set(token,userJson);
        redisTemplate.expire(token,30, TimeUnit.MINUTES);
        //RPC session
        //RpcContext.getContext().set("token",token);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(loadUser,userDto);
        userDto.setToken(token);
        return userDto;
    }
}
